package com.citic.topview.app.security;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.citic.topview.common.bean.Query;
import com.citic.topview.common.security.Principal;
import com.citic.topview.common.system.entity.User;
import com.citic.topview.system.service.UserService;

public class AppUserRealm extends AuthorizingRealm{

	@Autowired
    private UserService userService;
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		if (authcToken instanceof AppUsernamePasswordToken) {
			AppUsernamePasswordToken token = (AppUsernamePasswordToken) authcToken;
	        Map<String, Object> map = new LinkedHashMap<String, Object>();
	        map.put("loginName", token.getUsername());
	        User user = userService.getByUser(new Query(map));
			if (user != null) {
				if ("1".equals("0")){
					throw new AuthenticationException("msg:该已帐号禁止登录.");
				}
				
				return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()), user.getPassword(), getName());
			} else {
				throw new AuthenticationException("msg:该账号不存在。");
			}
		} else {
			return null;
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}
	
	@PostConstruct
	public void initCredentialsMatcher() {
		setCredentialsMatcher(new CustomCredentialsMatcher());
	}
	
	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}
	@Override
	public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}
	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}
	public void clearAllCachedAuthorizationInfo() {
		getAuthorizationCache().clear();
	}
	public void clearAllCachedAuthenticationInfo() {
		getAuthenticationCache().clear();
	}
	public void clearAllCache() {
		clearAllCachedAuthenticationInfo();
		clearAllCachedAuthorizationInfo();
	}
}
